package OnlineExam.display;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import java.util.*;
import java.text.*;
import OnlineExam.*;
import OnlineExam.question.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import OnlineExam.db.*;

/**
 *  Retrieve all the necessary information to display to a user his Question paper.
 */



public final class DisplayQuestionPaperAction extends Action 
{
    
    // The execute() method is where you provide your business logic
	//
	
    public ActionForward execute(ActionMapping mapping,ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
	{
		HttpSession session = request.getSession(); 
		String categoryId = request.getParameter("Category");
		
		//create a unique testId
		String testId = categoryId.concat (String.valueOf (System.currentTimeMillis()));
		DateFormat df = DateFormat.getInstance();
	
		
		try 
		{
			List list = DBUtil.select ("Category", "OnlineExam.Category", "CategoryId", categoryId);
			
			Category cat = (Category) list.listIterator().next();
			
	   		int [] qnumbers = null;	
		
			// generate the question numbers based on their type of generation (either Random or simle)
			//
			if ((cat.getQuestionGeneration()).equals("Random"))
				qnumbers = new RandomQuestionNumberGenerator().generateQuestionNumbers (categoryId);
			else 
				qnumbers = new SimpleQuestionNumberGenerator().generateQuestionNumbers (categoryId);

			long currTimeMillis = System.currentTimeMillis();
			long endTimeMillis = currTimeMillis + cat.getTimeLimit()* 60 * 1000;
		
			session.setAttribute("STARTTIMEMILLIS",currTimeMillis);
			session.setAttribute("ENDTIMEMILLIS", endTimeMillis);
			session.setAttribute("TESTID",testId);
	   		session.setAttribute ("QNUMBERS", qnumbers);
			session.setAttribute("CATEGORY", cat);
	   	
       		//  Create and return ActionForward object with "success" outcome
        	return (mapping.findForward("success"));
		}
		catch (Exception e)
		{
			System.out.println ("Exception " + e); 
			return (mapping.findForward ("dbError"));
		}
    }
}
